package com.wing.cms.tag;

import java.io.File;
import java.io.StringWriter;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import com.wing.common.Constants;
import com.wing.common.util.ApplicationPath;
import com.wing.common.util.RequestUtils;
import com.wing.common.util.SpringDI;
import com.wing.ext.domain.Products;
import com.wing.ext.service.ProductsManager;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class ShowProductTag extends BodyTagSupport {
	/**
	 * Process the start of this tag.
	 * 
	 * @exception JspException
	 *                if a JSP exception has occurred
	 */
	public int doStartTag() throws JspException {
		return (2);
	}

	/**
	 * Save the associated label from the body content (if any).
	 * 
	 * @exception JspException
	 *                if a JSP exception has occurred
	 */
	public int doAfterBody() throws JspException {
		return (SKIP_BODY);
	}

	/**
	 * Release any acquired resources.
	 */
	public void release() {
		super.release();
	}

	/**
	 * Process the end of this tag.
	 * <p>
	 * Support for indexed property since Struts 1.1
	 * 
	 * @exception JspException
	 *                if a JSP exception has occurred
	 */
	public int doEndTag() throws JspException {
		try {
			String pageId = (String) pageContext.getRequest().getAttribute("channelId");
			if (pageId == null || pageId.equals(""))throw new JspException("缺少文章id,无法渲染该块");
			String artId = pageId.split(",")[1];
			ProductsManager productsManager = (ProductsManager) SpringDI
					.getBean("productsManager");
			Products products = productsManager.findById(artId);
			
			String sitePath = RequestUtils.getSitePath(pageContext.getSession());
			StringWriter sw = new StringWriter();
			String templatesRoot = ApplicationPath.getParameter("appRoot")
					+ File.separator + "site" + File.separator
					+ sitePath + File.separator
					+ "framework" + File.separator + "template";

			Configuration cfg = new Configuration();
		
				cfg.setDirectoryForTemplateLoading(new File(templatesRoot));
				Template temp = cfg.getTemplate("showProduct.ftl");
				temp.process(products, sw);
			pageContext.getOut().write(sw.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return (EVAL_PAGE);
	}
}
